﻿# -*- coding: utf-8 -*-
import sys
import pickle
import numpy as np
import cv2
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
from skimage import transform
from keras.models import load_model
from keras.backend.tensorflow_backend import set_session
import os

os.environ["CUDA_VISIBLE_DEVICES"]="0"
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.45
set_session(tf.Session(config=config))
'''
input:
    1. 图片存储地址
    2. 图片索引文件地址
    3. 模型存储地址
    4. 结果输出地址

启动脚本输入示例
python /home/zjy/zjy_JupyterNotebook/street/1101/submit_use/test_score-streetmap-gs1104.py 
/home/zjy/zjy_JupyterNotebook/street/1101/submit_use/devpic 
/home/zjy/zjy_JupyterNotebook/street/1101/submit_use/picindex.csv 
/home/zjy/zjy_JupyterNotebook/street/1101/submit_use/model 
/home/zjy/zjy_JupyterNotebook/street/1101/submit_use/output.csv
'''

# PicRootPath = '/home/zjy/zjy_JupyterNotebook/street/1101/submit_use/devpic'
# PicIndexPath = '/home/zjy/zjy_JupyterNotebook/street/1101/submit_use/picindex.csv'
# ModelPath = '/home/zjy/zjy_JupyterNotebook/street/1101/submit_use/model'
# OutPath = '/home/zjy/zjy_JupyterNotebook/street/1101/submit_use/output.csv'

PicRootPath = sys.argv[1]
PicIndexPath = sys.argv[2]
ModelPath = sys.argv[3]
OutPath = sys.argv[4]

print('打印输入参数')
print(PicRootPath)
print(PicIndexPath)
print(ModelPath)
print(OutPath)

indexpd = pd.read_csv(PicIndexPath,header = None)
indexnp = np.array(indexpd)
# indexnp = np.loadtxt(PicIndexPath, dtype=np.str, delimiter=",")
print(indexnp)
reslen = len(indexnp)

#随机森林三通道模型
RFR_Model_NameArray = ["RFR_Model1.pickle","RFR_Model6.pickle","RFR_Model11.pickle","RFR_Model12.pickle"]
RFG_Model_NameArray = ["RFG_Model1.pickle","RFG_Model6.pickle","RFG_Model11.pickle","RFG_Model12.pickle"]
RFB_Model_NameArray = ["RFB_Model1.pickle","RFB_Model6.pickle","RFB_Model11.pickle","RFB_Model12.pickle"]

#可分离残差网络模型
SRNR_Model_NameArray = ["SRNR_Model1.h5","SRNR_Model6.h5","SRNR_Model11.h5","SRNR_Model12.h5"]
SRNG_Model_NameArray = ["SRNG_Model1.h5","SRNG_Model6.h5","SRNG_Model11.h5","SRNG_Model12.h5"]
SRNB_Model_NameArray = ["SRNB_Model1.h5","SRNB_Model6.h5","SRNB_Model11.h5","SRNB_Model12.h5"]

New_Model_NameArray = ["EnvSafe.h5","BuildingDestory.h5","StreetPermeability.h5"]

def myaccuracy(classes, logits):
    cp = tf.equal(tf.argmax(logits,1),tf.argmax(classes,1))
    acc = tf.reduce_mean(tf.cast(cp,"float"))
    return acc

def getRF_Model(RF_Model_NameArray):
    res = []
    for i in range(len(RF_Model_NameArray)):
        print('当前加载模型名：'+RF_Model_NameArray[i])
        file = open(ModelPath+"/"+RF_Model_NameArray[i], "rb")
        res.append(pickle.load(file))
    file.close()
    return res

def getDL_Model(DL_Model_NameArray):
    res = []
    for i in range(len(DL_Model_NameArray)):
        print('当前加载模型名：'+DL_Model_NameArray[i])
        res.append(load_model(ModelPath+"/"+DL_Model_NameArray[i],custom_objects={'myaccuracy': myaccuracy}))
    return res

print('加载R通道随机森林模型')
RFR_Model = getRF_Model(RFR_Model_NameArray)
print('加载G通道随机森林模型')
RFG_Model = getRF_Model(RFG_Model_NameArray)
print('加载B通道随机森林模型')
RFB_Model = getRF_Model(RFB_Model_NameArray)
print('加载R通道可分离残差网络模型')
SRNR_Model = getDL_Model(SRNR_Model_NameArray)
print('加载G通道可分离残差网络模型')
SRNG_Model = getDL_Model(SRNG_Model_NameArray)
print('加载B通道可分离残差网络模型')
SRNB_Model = getDL_Model(SRNB_Model_NameArray)

print('加载新可分离残差网络模型')
SRNW_Model = getDL_Model(New_Model_NameArray)

def outputScore(i,imgChannelR,imgChannelG,imgChannelB,imgChannelR3D,imgChannelG3D,imgChannelB3D):

    global RFR_Model
    global RFG_Model
    global RFB_Model
    global SRNR_Model
    global SRNG_Model
    global SRNB_Model

    #计算onehot编码概率
    RFR_Proba = RFR_Model[i].predict_proba(imgChannelR)
    RFG_Proba = RFG_Model[i].predict_proba(imgChannelG)
    RFB_Proba = RFB_Model[i].predict_proba(imgChannelB)

    SRNR_Proba = SRNR_Model[i].predict(imgChannelR3D)
    SRNG_Proba = SRNG_Model[i].predict(imgChannelG3D)
    SRNB_Proba = SRNB_Model[i].predict(imgChannelB3D)

    T_Proba  = RFR_Proba+RFG_Proba+RFB_Proba+SRNR_Proba+SRNG_Proba+SRNB_Proba

    return np.argmax(T_Proba,axis=1)[0]

def outputScore2(i,full_filename):
    image = cv2.imread(full_filename)
    image = cv2.resize(image / 255, (224, 224), interpolation=cv2.INTER_CUBIC)
    pred = SRNW_Model[i].predict(image[np.newaxis, :])
    pred = np.argmax(pred, axis=1)
    return pred[0]

def scoreCurPic(full_filename):
    #对图片按照指定大小进行数据解析和压缩
    #print(full_filename)
    res = [0,0,0,0,0,0,0]
    Height = 90
    Width = 150
    Dim = 1
    im = plt.imread(full_filename)
    im=transform.resize(im, (Height, Width))
    imgChannelR = im[:,:,0].reshape(-1,Height*Width*Dim)
    imgChannelG = im[:,:,1].reshape(-1,Height*Width*Dim)
    imgChannelB = im[:,:,2].reshape(-1,Height*Width*Dim)
    imgChannelR3D = im[:,:,0].reshape(-1,Height,Width,Dim)
    imgChannelG3D = im[:,:,1].reshape(-1,Height,Width,Dim)
    imgChannelB3D = im[:,:,2].reshape(-1,Height,Width,Dim)
    #按顺序对指标进行打分

    res[0] = outputScore2(0,full_filename)
    res[1] = outputScore(0,imgChannelR,imgChannelG,imgChannelB,imgChannelR3D,imgChannelG3D,imgChannelB3D)
    res[2] = outputScore2(1,full_filename)
    res[3] = outputScore2(2,full_filename)
    res[4] = outputScore(1,imgChannelR,imgChannelG,imgChannelB,imgChannelR3D,imgChannelG3D,imgChannelB3D)
    res[5] = outputScore(2,imgChannelR,imgChannelG,imgChannelB,imgChannelR3D,imgChannelG3D,imgChannelB3D)
    res[6] = outputScore(3,imgChannelR,imgChannelG,imgChannelB,imgChannelR3D,imgChannelG3D,imgChannelB3D)
    return res

# res = np.arange(reslen*10).reshape(reslen,10)
# res=[]
i=0
# 输出文件
f=open(OutPath,'w',encoding='utf-8')
arr_columns = ['', '环境安全感', '街道卫生性', '街道立面破败度', '低层建筑通透性', '建筑风貌', '围墙类型', '围墙连续性']
f.write('\t'.join(str(i) for i in  arr_columns))
f.write('\n')
direction = ['Back','Right','Left','Front' ] #因为每个索引有4 方向
# direction = ['Back' ,'Front' ]
for i in range(reslen):
    # print (i)
    for dire in direction:
        # CurPicFullPath = PicRootPath+"/"+dire+"/"+indexnp[i][0]+'_'+dire+'.jpg'
        CurPicFullPath = PicRootPath+"/"+indexnp[i][0]+"/"+indexnp[i][0]+'_'+dire+'.jpg'
        print(CurPicFullPath)
        if os.path.exists(CurPicFullPath):
            # res_this = scoreCurPic(CurPicFullPath)
            this_0 = []
            line = CurPicFullPath.split("/")[-1]
            for this_i in scoreCurPic(CurPicFullPath):  #这一步把每个打分降维
                # this_0.append(this_i[0])
                line += '\t'+ str(this_i)
                #print(line)
            line += '\n'
            f.write(line)
            # res.append(this_0)
f.close()
